package com.qianzhu8.kfc.demo.controller;

import com.alibaba.fastjson.JSON;
import com.qianzhu8.kfc.boot.client.KfcExecuteClient;
import com.qianzhu8.kfc.boot.model.KfcOrderModel;
import com.qianzhu8.kfc.boot.props.KfcProperty;
import com.qianzhu8.kfc.boot.request.GetKfcOrderByOrderNoRequest;
import com.qianzhu8.kfc.boot.request.PagedQueryKfcOrdersRequest;
import com.qianzhu8.kfc.boot.response.GetKfcOrderByOrderNoResponse;
import com.qianzhu8.kfc.boot.response.PagedQueryKfcOrdersResponse;
import com.qianzhu8.kfc.boot.util.SignUtils;
import com.qianzhu8.kfc.demo.model.OrderEventModel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * OrderController
 *
 * @author xuyanjun
 * @date 2020-05-03
 */
@Slf4j(topic = "OrderController")
@RestController
public class OrderController {

    @Autowired
    private KfcExecuteClient kfcExecuteClient;

    @Autowired
    private KfcProperty kfcProperty;

    @PostMapping("/kfcOrder/notify")
    public String onOrderEvent(@RequestBody OrderEventModel orderEventModel) {
        log.info("received kfc order message from qianzhu, message={}", JSON.toJSONString(orderEventModel));

        if (orderEventModel == null || orderEventModel.getEventType() == null) {
            log.error("kfc order message is illegal。[C101]");
            return "error";
        }

        // 校验签名
        checkSign(orderEventModel);

        final KfcOrderModel kfcOrderModel = getByOrderNo(orderEventModel.getOrderNo());
        if (kfcOrderModel == null) {
            log.error("get kfc order error。[C102]");
            return "error";
        }

        switch (orderEventModel.getEventType()) {
            // 部分取消
            case -3:
                // todo 发送部分取消的通知给用户
                break;
            // 全部取消
            case -5:
                // todo 发送取消的通知给用户
                break;
            // 完成
            case 10:
                // todo 发送已出票的通知给用户
                break;
            // 非法事件
            default:
                log.error("kfc order message is illegal。[C999]");
                return "error";
        }

        return "success";
    }

    /**
     * 校验签名
     *
     * @param orderEventModel orderEventModel
     */
    private void checkSign(OrderEventModel orderEventModel) {
        Map<String, String> requestMap = new HashMap<>(8);
        requestMap.put("orderNo", orderEventModel.getOrderNo());
        requestMap.put("eventType", orderEventModel.getEventType().toString());
        requestMap.put("platformId", orderEventModel.getPlatformId().toString());
        requestMap.put("platform", orderEventModel.getPlatform());

        final String sign = SignUtils.generateSign(requestMap, kfcProperty.getSecret());
        Assert.isTrue(sign.equalsIgnoreCase(orderEventModel.getSign()), "签名校验失败。");
    }

    /**
     * 根据订单号获取订单
     *
     * @param orderNo 订单号
     * @return 订单
     */
    private KfcOrderModel getByOrderNo(String orderNo) {
        GetKfcOrderByOrderNoRequest request = new GetKfcOrderByOrderNoRequest();
        request.setOrderNo(orderNo);

        final GetKfcOrderByOrderNoResponse kfcOrderByOrderNoResponse = kfcExecuteClient.execute(request);
        log.info("get kfc order,order={}", JSON.toJSONString(kfcOrderByOrderNoResponse));

        if (kfcOrderByOrderNoResponse == null) {
            log.warn("get kfc order error,orderNo={} [C104]", orderNo);
            return null;
        }
        if (!Boolean.TRUE.equals(kfcOrderByOrderNoResponse.getSuccess())) {
            log.warn("get kfc order error,orderNo={} [C105]", orderNo);
            return null;
        }

        return kfcOrderByOrderNoResponse.getData();
    }

    /**
     * 分页查询订单
     */
    @GetMapping("/kfcOrder/pagedQuery")
    public List<KfcOrderModel> pagedQuery() {
        PagedQueryKfcOrdersRequest request = new PagedQueryKfcOrdersRequest();
        request.setPageIndex(1)
                .setPageSize(100)
                .setUpdateTimeBeginTime("2020-06-16 12:00:00")
                .setUpdateTimeEndTime("2020-06-16 12:00:00");

        final PagedQueryKfcOrdersResponse pagedQueryKfcOrdersResponse = kfcExecuteClient.execute(request);

        return pagedQueryKfcOrdersResponse.getData();
    }
}
